#!/usr/bin/python
# Py-to-RED
# Python to REDLisp Code Converter
# Copyright 2006 Rudolf Olah

from string import strip, replace, find
from sys import argv, exit
from os import mkdir
from os.path import exists

module_equals = {"pygtk":"gtk", "os":"fileio\" \"math"}
function_equals = {"while":"while\n", "print":"print", "len":"len"}

def clean (line):
  newline = strip (line)
  count = find (newline, "  ")/2
  i = 0
  while i < count:
    newline = replace (newline, "  ", " ")
    i += 1
  return newline

def convert_import (source, line):
  module = ""
  blah = line.find (" ")+1
  if (line[:4] == "from"):
    module = line[blah:line.find (" ", blah)]
  else:
    module = line[blah:]
  try:
    source.write ("(load \"" + module_equals[module] + "\")\n")
  except KeyError:
    print "convert_import::Non-standard module"

def convert_function (source, line):
  source.write ("\n(function " + line[line.find (" ")+1:line.find (":")])
  source.write ("\n  ")
  source.write ("\n)\n")

def convert (source, line):
  line = clean (line)
  if (line[:1] == "#"):
    source.write ("//" + line[1:] + "\n")
  elif (line[:4] == "from") or (line[:6] == "import"):
    convert_import (source, line)
  elif (line[:3] == "def"):
    convert_function (source, line)
  elif (line.find ("=") > -1):
    source.write ("(\'" + clean (line[:line.find ("=")]) + " ")
    convert (source, line[line.find ("=")+1:])
    source.write (")\n")
  else:
    source.write ("(")
    try:
      source.write (function_equals[line[:line.find (" ")]])
    except KeyError:
      source.write (line[:line.find (" ")])
    source.write (")")

def convert_file (infile, source):
  source.write ("// Converted from " + infile.name + " by Py-to-RED\n")
  line = infile.readline ()
  if (line[:2] == "#!"):
    line = infile.readline ()
  while line:
    convert (source, line)
    line = infile.readline ()

print "Py-to-RED Code Converter\nCopyright 2006 Rudolf Olah"
try:
  print "Opening " + argv[1] + " for conversion..."
except IndexError:
  print "Usage:\n\tpy-to-red.py [filename]"
  exit ()
infile = open (argv[1], "r")
source = open (argv[1][:-2] + "dlisp", "w")
convert_file (infile, source)
print "Converted from Python to REDLisp successfully :D"